# import requests, json
#
#
# class BaiduApi():
#     def __init__(self):
#         self.API_KEY = "bce-v3/ALTAK-rOvrXX5rPmIXQRNrybptm/9281000c702a2b9d0d474653b50ba1635d2cc451"
#         self.SECRET_KEY = "5af587c43c4041e89ff2c6ff93db9f05"
#
#     def get_access_token(self):
#         """
#     使用 AK，SK 生成鉴权签名（Access Token）
#     :return: access_token，或是None(如果错误)
#     """
#         url = "https://aip.baidubce.com/oauth/2.0/token"
#         params = {"grant_type": "client_credentials", "client_id": self.API_KEY, "client_secret": self.SECRET_KEY}
#         return str(requests.post(url, params=params).json().get("access_token"))
#
#     # 身份证验证
#     def idcard(self, picurl):
#         url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + self.get_access_token()
#
#         # image 可以通过 get_file_content_as_base64("C:\fakepath\1.png",True) 方法获取
#         payload = 'id_card_side=front&url=%s&detect_ps=false&detect_risk=false&detect_quality=false&detect_photo=false&detect_card=false&detect_direction=false' % (
#             picurl)
#         headers = {
#             'Content-Type': 'application/x-www-form-urlencoded',
#             'Accept': 'application/json'
#         }
#
#         response = requests.request("POST", url, headers=headers, data=payload)
#         print(response.text)
#         return response
#
#     # 文字识别
#     def fontmessage(self, picurl):
#         url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=" + self.get_access_token()
#
#         payload = 'url=%s&detect_direction=false&paragraph=false&probability=false' % (picurl)
#         headers = {
#             'Content-Type': 'application/x-www-form-urlencoded',
#             'Accept': 'application/json'
#         }
#         response = requests.request("POST", url, headers=headers, data=payload)
#         data = json.loads(response.text)
#         print(data)
#         name = data['words_result'][0]['words']
#         code = data['words_result'][1]['words']
#         return {"name": name, 'code': code}
#
#
# bdapi = BaiduApi()
# # data = bdapi.fontmessage("C:\Users\86139\Desktop\view.jpg")
# # print(data)


# import urllib
# import urllib.parse
# import base64
# import json
# import requests
# from user.models import User
# from user.ser import UserSer
# from utils.tooljwt import myjwt
#
#
# class BaiduApi:
#     def __init__(self):
#         self.API_KEY = "bce-v3/ALTAK-rOvrXX5rPmIXQRNrybptm/9281000c702a2b9d0d474653b50ba1635d2cc451"
#         self.SECRET_KEY = "5af587c43c4041e89ff2c6ff93db9f05"
#
#     def get_access_token(self):
#         """
#         使用 AK，SK 生成鉴权签名（Access Token）
#         :return: access_token，或是None(如果错误)
#         """
#         url = "https://aip.baidubce.com/oauth/2.0/token"
#         print(url)
#         params = {"grant_type": "client_credentials", "client_id": self.API_KEY, "client_secret": self.SECRET_KEY}
#         print(str(requests.post(url, params=params).json().get("access_token")))
#         return str(requests.post(url, params=params).json().get("access_token"))
#
#     def idcard(self, imgurl, request):
#         print(self.get_access_token())
#         url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + self.get_access_token()
#         payload = f'id_card_side=front&url={imgurl}&detect_ps=false&detect_risk=false&detect_quality=false&detect_photo=false&detect_card=false&detect_direction=false'
#         headers = {
#             'Content-Type': 'application/x-www-form-urlencoded',
#             'Accept': 'application/json'
#         }
#
#         response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))
#         import json
#
#         # 假设 response.text 的内容存储在 idCardData
#
#         idCardData = response.text
#         # 将 JSON 字符串解析为 Python 字典
#         id_card_dict = json.loads(idCardData)
#         print(id_card_dict)
#         # 提取信息
#         name = id_card_dict["words_result"]["姓名"]["words"]
#         nationality = id_card_dict["words_result"]["民族"]["words"]
#         address = id_card_dict["words_result"]["住址"]["words"]
#         id_number = id_card_dict["words_result"]["公民身份号码"]["words"]
#         birth_date = id_card_dict["words_result"]["出生"]["words"]
#         gender = id_card_dict["words_result"]["性别"]["words"]
#         print("姓名:", name)
#         print("民族:", nationality)
#         print("住址:", address)
#         print("公民身份号码:", id_number)
#         print("出生日期:", birth_date)
#         print("性别:", gender)
#
#         token = request.headers.get('Authorization').split(' ')[1]
#         data = myjwt.jwt_decode(token)
#         user = User.objects.filter(userid=data['id']).first()
#         card = {
#             "userid": data['id'],
#             "name": name,
#             "nationality": nationality,
#             "address": address,
#             "id_number": id_number,
#             "birth_date": birth_date,
#             "gender": gender
#         }
#         print("eqweqweqw")
#         if user:
#             return '已经存在'
#         else:
#             ser = UserSer(data=card)
#             print("232326")
#             if ser.is_valid():
#                 print("2323232")
#                 ser.save()
#             return ser.data
#
#
#
#
# bdapi = BaiduApi()
# data = bdapi.get_id_card("https://www.baidu.com/img/bd_logo1.png")
# print(data)

#
# import requests
# from user.models import User
# from user.ser import UserSer
# from utils.tooljwt import myjwt
#
#
# class BaiduApi:
#     def __init__(self):
#         self.API_KEY = "7EvaI68Mjuba8M2xZ8zzPplo"
#         self.SECRET_KEY = "1467ec12ed6f40d99c92bc4fc29857bd"
#
#     def get_access_token(self):
#         url = "https://aip.baidubce.com/oauth/2.0/token"
#         params = {
#             "grant_type": "client_credentials",
#             "client_id": self.API_KEY,
#             "client_secret": self.SECRET_KEY
#         }
#         print(url)
#         print(params)
#         try:
#             # 忽略 SSL 验证
#             response = requests.post(url, params=params, verify=False)
#             print(response)
#             response.raise_for_status()  # 检查请求是否成功
#             # print(response.raise_for_status())
#             access_token = response.json().get("access_token")
#             # print(f"成功获取 Access Token: {access_token}")
#             return access_token
#         except requests.RequestException as e:
#             # print(f"请求失败，状态码: {response.status_code}")
#             # print(f"响应内容: {response.text}")
#             # print(f"获取百度 Access Token 失败: {str(e)}")
#             return None
#         # url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={self.API_KEY}&client_secret={self.SECRET_KEY}"
#         # # print(url)
#         # response = requests.get(url)
#         # # print(response)
#         # response.raise_for_status()
#         # print(response.raise_for_status())
#         # access_token = response.json().get("access_token")
#         # # print(access_token)
#
#     def idcard(self, imgurl, request):
#         access_token = self.get_access_token()
#         if not access_token:
#             return {"code": 500, "msg": "获取百度 Access Token 失败"}
#
#         url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token={access_token}"
#         payload = f'id_card_side=front&url={imgurl}&detect_ps=false&detect_risk=false&detect_quality=false&detect_photo=false&detect_card=false&detect_direction=false'
#         headers = {
#             'Content-Type': 'application/x-www-form-urlencoded',
#             'Accept': 'application/json'
#         }
#
#         try:
#             response = requests.post(url, headers=headers, data=payload.encode("utf-8"))
#             response.raise_for_status()  # 检查请求是否成功
#             id_card_dict = response.json()
#             print(id_card_dict)
#
#             # 检查是否包含 'words_result' 键
#             if 'words_result' not in id_card_dict:
#                 return {"code": 500, "msg": f"百度 OCR 响应中缺少 'words_result' 键: {id_card_dict}"}
#
#             # 提取信息
#             name = id_card_dict["words_result"]["姓名"]["words"]
#             nationality = id_card_dict["words_result"]["民族"]["words"]
#             address = id_card_dict["words_result"]["住址"]["words"]
#             id_number = id_card_dict["words_result"]["公民身份号码"]["words"]
#             birth_date = id_card_dict["words_result"]["出生"]["words"]
#             gender = id_card_dict["words_result"]["性别"]["words"]
#             print("姓名:", name)
#             print("民族:", nationality)
#             print("住址:", address)
#             print("公民身份号码:", id_number)
#             print("出生日期:", birth_date)
#             print("性别:", gender)
#
#             token = request.headers.get('Authorization')
#             if token:
#                 token = token.split(' ')[1]
#             else:
#                 return {"code": 401, "msg": "未提供有效的授权令牌"}
#
#             data = myjwt.jwt_decode(token)
#             user = User.objects.filter(userid=data['id']).first()
#             card = {
#                 "userid": data['id'],
#                 "name": name,
#                 "nationality": nationality,
#                 "address": address,
#                 "id_number": id_number,
#                 "birth_date": birth_date,
#                 "gender": gender
#             }
#             print("eqweqweqw")
#             if user:
#                 return {"code": 409, "msg": "用户已经存在"}
#             else:
#                 ser = UserSer(data=card)
#                 print("232326")
#                 if ser.is_valid():
#                     print("2323232")
#                     ser.save()
#                     return {"code": 200, "msg": "用户信息保存成功", "data": ser.data}
#                 else:
#                     return {"code": 400, "msg": "用户信息验证失败", "errors": ser.errors}
#         except requests.RequestException as e:
#             return {"code": 500, "msg": f"百度 OCR 请求失败: {str(e)}"}
#         except KeyError as e:
#             return {"code": 500, "msg": f"解析百度 OCR 响应失败: {str(e)}"}
#         except Exception as e:
#             return {"code": 500, "msg": f"发生未知错误: {str(e)}"}
#
#
# bdapi = BaiduApi()

#
# import requests
# import json
# class Baiduapi():
#     def __init__(self):
#         self.API_KEY = "H3J4QnloAKrk4LUQbL5Qh3la"
#         self.SECRET_KEY = "NbLZ9n6nMsn3L1dhHicrW547VIwsnmyd"
#         # self.API_KEY = "TGRprwrLbNVttTwx7JR87fPL"
#         # self.SECRET_KEY = "O9PAIRrbYNictQszm0HXwsZMsPAE1ybL"
#
#     def get_access_token(self):
#         """
#         使用 AK，SK 生成鉴权签名（Access Token）
#         :return: access_token，或是None(如果错误)
#         """
#         url = "https://aip.baidubce.com/oauth/2.0/token"
#         params = {"grant_type": "client_credentials", "client_id": self.API_KEY, "client_secret": self.SECRET_KEY}
#         return str(requests.post(url, params=params).json().get("access_token"))
#
#     def idcard(self,picurl):
#             url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + self.get_access_token()
#
#             payload = f'id_card_side=front&url={picurl}&detect_ps=false&detect_risk=false&detect_quality=false&detect_photo=false&detect_card=false&detect_direction=false'
#             headers = {
#                 'Content-Type': 'application/x-www-form-urlencoded',
#                 'Accept': 'application/json'
#             }
#
#             response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))
#             # print(response.text)
#             data = json.loads(response.text)
#             print(data)
#             # return data
#             name = data['words_result']['姓名']['words']
#             code = data['words_result']['公民身份号码']['words']
#             return {"name": name,"codeid":code}
#
#     def fontmessage(self, picurl):
#         url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=" + self.get_access_token()
#
#         payload = 'url=%s&detect_direction=false&paragraph=false&probability=false' % (picurl)
#         headers = {
#             'Content-Type': 'application/x-www-form-urlencoded',
#             'Accept': 'application/json'
#         }
#         response = requests.request("POST", url, headers=headers, data=payload)
#         print(response.text)
#         data = json.loads(response.text)
#         name = data['words_result'][1]['words']
#         code = data['words_result'][12]['words']
#         return {"name": name, 'code': code}
#
#     def car_card(self, picurl):
#         url = "https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate?access_token=" + self.get_access_token()
#
#         payload = 'url=%s&multi_detect=false&multi_scale=false&detect_complete=false&detect_risk=false'%(picurl)
#         headers = {
#             'Content-Type': 'application/x-www-form-urlencoded',
#             'Accept': 'application/json'
#         }
#
#         response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))
#         data= json.loads(response.text)
#         # return data
#         car= data['words_result']['number']
#         return {"car_number": car}
#
#
# bdapi = Baiduapi()


import requests
import json
from user import models
from user.ser import IdentitySer


class Baiduapi():
    def __init__(self):
        self.API_KEY = "H3J4QnloAKrk4LUQbL5Qh3la"
        self.SECRET_KEY = "NbLZ9n6nMsn3L1dhHicrW547VIwsnmyd"
        # self.API_KEY = "7EvaI68Mjuba8M2xZ8zzPplo"
        # self.SECRET_KEY = "1467ec12ed6f40d99c92bc4fc29857bd"
        # self.API_KEY = "TGRprwrLbNVttTwx7JR87fPL"
        # self.SECRET_KEY = "O9PAIRrbYNictQszm0HXwsZMsPAE1ybL"

    def get_access_token(self):
        """
        使用 AK，SK 生成鉴权签名（Access Token）
        :return: access_token，或是None(如果错误)
        """
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {"grant_type": "client_credentials", "client_id": self.API_KEY, "client_secret": self.SECRET_KEY}
        try:
            response = requests.post(url, params=params)
            print(response)
            response.raise_for_status()
            return response.json().get("access_token")
        except requests.RequestException as e:
            print(f"获取 Access Token 失败: {e}")
            return None

    def idcard(self, picurl):
        access_token = self.get_access_token()
        if not access_token:
            return {"error": "获取 Access Token 失败"}
        url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token={access_token}"
        payload = f'id_card_side=front&url={picurl}&detect_ps=false&detect_risk=false&detect_quality=false&detect_photo=false&detect_card=false&detect_direction=false'
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }
        try:
            response = requests.post(url, headers=headers, data=payload.encode("utf-8"))
            response.raise_for_status()
            data = response.json()
            # print(data)
            if 'words_result' not in data:
                return {"error": f"响应中缺少 'words_result' 键: {data}"}
            name = data['words_result']['姓名']['words']
            code = data['words_result']['公民身份号码']['words']
            identity = {
                "name": name,
                'identification': code
            }
            ident = IdentitySer(data=identity)
            if ident.is_valid():
                ident.save()
                return {"name": name, "codeid": code}
            return {"name": name, "codeid": code}
        except requests.RequestException as e:
            return {"error": f"请求身份证识别接口失败: {e}"}
        except KeyError as e:
            return {"error": f"解析身份证识别结果失败: {e}"}

    def fontmessage(self, picurl):
        access_token = self.get_access_token()
        # print(access_token,11111111111111111)
        if not access_token:
            return {"error": "获取 Access Token 失败"}
        url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token={access_token}"
        payload = f'url={picurl}&detect_direction=false&paragraph=false&probability=false'
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }
        # print(url,11111111111111)
        try:
            response = requests.post(url, headers=headers, data=payload)
            # print(response)
            response.raise_for_status()
            data = response.json()
            # print(data)
            if 'words_result' not in data:
                return {"error": f"响应中缺少 'words_result' 键: {data}"}
            if len(data['words_result']) < 13:
                return {"error": "识别结果中 'words_result' 长度不足"}
            name = data['words_result'][1]['words']
            code = data['words_result'][12]['words']
            return {"name": name, 'code': code}
        except requests.RequestException as e:
            return {"error": f"请求精确文字识别接口失败: {e}"}
        except KeyError as e:
            return {"error": f"解析精确文字识别结果失败: {e}"}

    def car_card(self, picurl):
        access_token = self.get_access_token()
        if not access_token:
            return {"error": "获取 Access Token 失败"}
        url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate?access_token={access_token}"
        payload = f'url={picurl}&multi_detect=false&multi_scale=false&detect_complete=false&detect_risk=false'
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }
        try:
            response = requests.post(url, headers=headers, data=payload.encode("utf-8"))
            response.raise_for_status()
            data = response.json()
            # print(data)
            if 'words_result' not in data:
                return {"error": f"响应中缺少 'words_result' 键: {data}"}
            car = data['words_result']['number']
            return {"car_number": car}
        except requests.RequestException as e:
            return {"error": f"请求车牌识别接口失败: {e}"}
        except KeyError as e:
            return {"error": f"解析车牌识别结果失败: {e}"}


bdapi = Baiduapi()
